package cn.cnf.service.impl;

import cn.cnf.common.enums.VerifyState;
import cn.cnf.common.enums.WorkType;
import cn.cnf.common.exception.CustomException;
import cn.cnf.common.utils.UserRequestUtil;
import cn.cnf.entity.Chapter;
import cn.cnf.entity.Comic;
import cn.cnf.entity.Novel;
import cn.cnf.entity.User;
import cn.cnf.mapper.ChapterMapper;
import cn.cnf.service.ChapterService;
import cn.cnf.service.ComicService;
import cn.cnf.service.NovelService;
import cn.cnf.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 服务接口实现
 *
 * @author ZhuMeiYi
 * @description
 * @since 2020-12-04 15:18:43
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Service
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    private final ChapterMapper chapterMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ComicService comicService;
    @Autowired
    private NovelService novelService;

    @Override
    public List<Chapter> selectByFromId(String fromId, WorkType type, VerifyState state) {
        // 检查来源id和类型 根据创建时间排序
        LambdaQueryWrapper<Chapter> list = new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getFromId, fromId)
                .eq(Chapter::getType, type.getValue())
                .orderByAsc(Chapter::getCreateTime);

        if (state!=null){
            list.eq( Chapter::getVerifyState, state.getValue());
        }

        return chapterMapper.selectList(list);
    }

    @Override
    public IPage<Chapter> selectByState(Integer current, Integer pageSize, VerifyState state) {
        // 设置状态
        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<Chapter>().eq(Chapter::getVerifyState, state.getValue());
        Page<Chapter> page = new Page<>(current, pageSize);
        return chapterMapper.selectPage(page, wrapper);
    }

    @Override
    public Integer chapterVerify(String chapterId,WorkType workType, VerifyState state) {
        if (state == null) {
            throw new CustomException("状态值非法");
        }
        Chapter old = getById(chapterId);
        if (old==null){
            throw new CustomException("没有找到对应章节");
        }else if (old.getVerifyState().equals(state.getValue())){
            throw new CustomException("当前状态无需更改");
        }

        Chapter chapter = new Chapter();
        chapter.setId(chapterId);
        chapter.setType(workType.getValue());
        chapter.setVerifyState(state.getValue());
        if (!updateById(chapter)) {
            throw new CustomException("审核失败");
        }
        // 如果是审核完成
        if (state.equals(VerifyState.VERIFIED)){
            Chapter last = getById(chapterId);
            if (workType.equals(WorkType.COMIC)){
                Comic comic = new Comic();
                comic.setId(last.getFromId());
                comic.setLastChapterId(last.getId());
                comic.setLastChapterTitle(last.getChapterName());
                comicService.updateById(comic);
            }else if (workType.equals(WorkType.NOVEL)){
                Novel novel = new Novel();
                novel.setId(last.getFromId());
                novel.setLastChapterId(last.getId());
                novel.setLastChapterTitle(last.getChapterName());
                novelService.updateById(novel);
            }else {
                throw new CustomException("作品类型未知");
            }
        }

        return state.getValue();
    }

    @Override
    public String addOrUpdateChapter(Chapter chapter) {

        if (StringUtils.isBlank(chapter.getFromId())){
            throw new CustomException("作品来源id为空");
        }

        WorkType type = WorkType.getByValue(chapter.getType());
        if (type==null){
            throw new CustomException("不存在的作品类型");
        }
        if(StringUtils.isBlank(chapter.getChapterName())){
            throw new CustomException("章节标题为空");
        }
        if (type.equals(WorkType.COMIC)){
            if (comicService.getById(chapter.getFromId())==null){
                throw new CustomException("没有找到对应漫画");
            }
        }else if (type.equals(WorkType.NOVEL)){
            if (novelService.getById(chapter.getFromId())==null){
                throw new CustomException("没有找到对应小说");
            }
        }
        // 设置本章审核状态
        chapter.setVerifyState(VerifyState.VERIFYING.getValue());
        // 设置作者
        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
        chapter.setAuthorId(user.getId());
        saveOrUpdate(chapter);
        return chapter.getId();
    }

    /**
     * 获取章节 根据身份给审核过了的
     *
     * @param fromId
     * @return
     */
    @Override
    public List<Chapter> getChapterById(String fromId,WorkType type) {

        if (type==null){
            throw new CustomException("未知的作品类型");
        }
        if (type.equals(WorkType.COMIC)&&(comicService.getById(fromId)==null)){
            throw new CustomException("没有找到对应漫画");
        } else if (type.equals(WorkType.NOVEL)&&(novelService.getById(fromId)==null)){
            throw new CustomException("没有找到对应小说");
        }

        String role = UserRequestUtil.getCurrentUserRole();
        if (StringUtils.isNotBlank(role)) {
            // 如果是管理员 返回全部
            if (role.contains("ADMIN")) {
                return selectByFromId(fromId, type, null);
            }
        }

        // 如果用户登录了
        String userName = UserRequestUtil.getCurrentUserName();
        if (StringUtils.isNotBlank(userName)) {
            User user = userService.findUserByUsername(userName);
            // 判断是否为作者 作者可以看自己审核中的
            if (type.equals(WorkType.COMIC)){
                if (comicService.isAuthor(fromId,user.getId())) {
                    return selectByFromId(fromId, WorkType.COMIC, null);
                }
            }else if (type.equals(WorkType.NOVEL)){
                if (novelService.isAuthor(fromId,user.getId())){
                    return selectByFromId(fromId, WorkType.NOVEL, null);
                }
            }

        }
        return selectByFromId(fromId, type, VerifyState.VERIFIED);
    }

    @Override
    public boolean delete(String fromId, WorkType type) {
        return remove(new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getFromId, fromId)
                .eq(Chapter::getType, type.getValue()));
    }

    @Override
    public List<Chapter> getVerifyingChapter(String fromId, WorkType type) {

        if (type.equals(WorkType.COMIC)){
            if (comicService.getById(fromId)==null){
                throw new CustomException("没有找到对应漫画");
            }
        }else if (type.equals(WorkType.NOVEL)){
            if (novelService.getById(fromId)==null){
                throw new CustomException("没有找到对应小说");
            }
        }

        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getFromId, fromId)
                .eq(Chapter::getType, type.getValue())
                .eq(Chapter::getVerifyState,VerifyState.VERIFYING.getValue());
        return list(wrapper);
    }
}